/**
 * 消息通知状态管理
 */

import { defineStore } from 'pinia'

export const useNotificationStore = defineStore('notification', {
  state: () => {
    const messages = [
      {
        id: 1,
        type: 'system',
        title: '系统维护通知',
        content: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用。',
        isRead: false,
        createTime: '2024-01-15 10:00:00',
        priority: 'high'
      },
      {
        id: 2,
        type: 'order',
        title: '新订单提醒',
        content: '您有一个新的销售订单需要处理，订单号：SO20240115001',
        isRead: false,
        createTime: '2024-01-15 09:30:00',
        priority: 'medium',
        orderId: 1
      },
      {
        id: 3,
        type: 'inventory',
        title: '库存预警',
        content: '商品"iPhone 15"库存不足，当前库存：5台，建议及时补货。',
        isRead: true,
        createTime: '2024-01-15 08:15:00',
        priority: 'high',
        productId: 1
      },
      {
        id: 4,
        type: 'approval',
        title: '审批待处理',
        content: '您有一个采购订单需要审批，订单号：PO20240115002',
        isRead: false,
        createTime: '2024-01-15 07:45:00',
        priority: 'medium',
        orderId: 2
      },
      {
        id: 5,
        type: 'system',
        title: '数据备份完成',
        content: '系统数据备份已完成，备份文件已保存至安全位置。',
        isRead: true,
        createTime: '2024-01-14 23:30:00',
        priority: 'low'
      }
    ]
    
    // 计算初始未读数量
    const unreadCount = messages.filter(msg => !msg.isRead).length
    
    return {
      // 未读消息数量
      unreadCount,
      // 消息列表
      messages,
      // 通知设置
      settings: {
        enableSound: true,
        enableDesktop: true,
        enableEmail: false,
        types: {
          system: true,
          order: true,
          inventory: true,
          approval: true,
          finance: true
        }
      }
    }
  },

  getters: {
    // 获取未读消息
    unreadMessages: (state) => {
      return state.messages.filter(msg => !msg.isRead)
    },

    // 获取已读消息
    readMessages: (state) => {
      return state.messages.filter(msg => msg.isRead)
    },

    // 按类型获取消息
    getMessagesByType: (state) => {
      return (type) => state.messages.filter(msg => msg.type === type)
    },

    // 按优先级获取消息
    getMessagesByPriority: (state) => {
      return (priority) => state.messages.filter(msg => msg.priority === priority)
    },

    // 获取高优先级未读消息
    highPriorityUnread: (state) => {
      return state.messages.filter(msg => !msg.isRead && msg.priority === 'high')
    }
  },

  actions: {
    // 添加消息
    addMessage(message) {
      const newMessage = {
        id: Date.now(),
        type: 'system',
        title: '',
        content: '',
        isRead: false,
        createTime: new Date().toLocaleString(),
        priority: 'medium',
        ...message
      }
      
      this.messages.unshift(newMessage)
      this.updateUnreadCount()
      
      // 如果启用了桌面通知
      if (this.settings.enableDesktop && 'Notification' in window) {
        this.showDesktopNotification(newMessage)
      }
      
      return newMessage
    },

    // 标记消息为已读
    markAsRead(messageId) {
      const message = this.messages.find(msg => msg.id === messageId)
      if (message && !message.isRead) {
        message.isRead = true
        this.updateUnreadCount()
      }
    },

    // 标记所有消息为已读
    markAllAsRead() {
      this.messages.forEach(msg => {
        msg.isRead = true
      })
      this.updateUnreadCount()
    },

    // 删除消息
    deleteMessage(messageId) {
      const index = this.messages.findIndex(msg => msg.id === messageId)
      if (index > -1) {
        this.messages.splice(index, 1)
        this.updateUnreadCount()
      }
    },

    // 清空所有消息
    clearAllMessages() {
      this.messages = []
      this.updateUnreadCount()
    },

    // 更新未读数量
    updateUnreadCount() {
      this.unreadCount = this.messages.filter(msg => !msg.isRead).length
    },

    // 显示桌面通知
    showDesktopNotification(message) {
      if (Notification.permission === 'granted') {
        const notification = new Notification(message.title, {
          body: message.content,
          icon: '/favicon.ico',
          tag: `message-${message.id}`
        })
        
        notification.onclick = () => {
          window.focus()
          this.markAsRead(message.id)
          notification.close()
        }
        
        // 5秒后自动关闭
        setTimeout(() => {
          notification.close()
        }, 5000)
      }
    },

    // 请求通知权限
    requestNotificationPermission() {
      if ('Notification' in window && Notification.permission === 'default') {
        Notification.requestPermission().then(permission => {
          if (permission === 'granted') {
            this.settings.enableDesktop = true
          }
        })
      }
    },

    // 更新通知设置
    updateSettings(newSettings) {
      this.settings = { ...this.settings, ...newSettings }
      
      // 保存到本地存储
      localStorage.setItem('notificationSettings', JSON.stringify(this.settings))
    },

    // 从本地存储加载设置
    loadSettings() {
      const saved = localStorage.getItem('notificationSettings')
      if (saved) {
        this.settings = { ...this.settings, ...JSON.parse(saved) }
      }
    },

    // 发送系统通知
    sendSystemNotification(title, content, priority = 'medium') {
      return this.addMessage({
        type: 'system',
        title,
        content,
        priority
      })
    },

    // 发送订单通知
    sendOrderNotification(orderId, orderNo, type = 'new') {
      const titles = {
        new: '新订单提醒',
        update: '订单更新',
        cancel: '订单取消'
      }
      
      const contents = {
        new: `您有一个新的销售订单需要处理，订单号：${orderNo}`,
        update: `订单 ${orderNo} 状态已更新`,
        cancel: `订单 ${orderNo} 已被取消`
      }
      
      return this.addMessage({
        type: 'order',
        title: titles[type],
        content: contents[type],
        priority: type === 'new' ? 'high' : 'medium',
        orderId
      })
    },

    // 发送库存通知
    sendInventoryNotification(productId, productName, stock, type = 'low') {
      const titles = {
        low: '库存预警',
        out: '库存不足',
        negative: '负库存警告'
      }
      
      const contents = {
        low: `商品"${productName}"库存不足，当前库存：${stock}，建议及时补货。`,
        out: `商品"${productName}"库存为零，请立即补货。`,
        negative: `商品"${productName}"出现负库存，请检查库存数据。`
      }
      
      return this.addMessage({
        type: 'inventory',
        title: titles[type],
        content: contents[type],
        priority: 'high',
        productId
      })
    },

    // 发送审批通知
    sendApprovalNotification(orderId, orderNo, type = 'pending') {
      const titles = {
        pending: '审批待处理',
        approved: '审批通过',
        rejected: '审批拒绝'
      }
      
      const contents = {
        pending: `您有一个采购订单需要审批，订单号：${orderNo}`,
        approved: `采购订单 ${orderNo} 审批已通过`,
        rejected: `采购订单 ${orderNo} 审批被拒绝`
      }
      
      return this.addMessage({
        type: 'approval',
        title: titles[type],
        content: contents[type],
        priority: type === 'pending' ? 'medium' : 'low',
        orderId
      })
    }
  }
})
